import {Button, Descriptions, message, Result,Popconfirm, Spin} from 'antd';
import {PageHeaderWrapper, RouteContext } from '@ant-design/pro-layout';
import React, { Fragment, useEffect, useState } from 'react';
import { connect, history } from 'umi';
import moment from 'moment';
import styles from './style.less';
import { getEmployeeById } from './service';
import { deleteEmployeeById } from '../service';
import './index.less';
import { maritalList, healthsList,yesOrNoList, inOrgList, genderList,regionList,nationList} from '@/utils/constant'
import BasisInfo from './components/BasisInfo';
import Score from './components/Score';
import Annex from './components/Annex';
import Contract from './components/Contract';
import Attendance from './components/Attendance';
import Performance from './components/Performance';
import Salary from './components/Salary';
import Record from './components/Record';
import Hire from './components/Hire';
import Certificate from './components/Certificate';
import Internal from './components/Internal';

const Details = (props) => {
  const { dispatch, infoModel, currentUser } = props;
  const { options = {} } = infoModel;
  const { orgLine = [], orgSystem = [], nativePlace = [],jobLevel = [] } = options;
  const { authorities } = currentUser;
  const [tabActiveKey, setTabActiveKey] = useState('basisInfo');
  const [info, setInfo] = useState({});
  const [tabList,setTabList] = useState([]);

  useEffect(() => {
    const { employeeId } = props.match.params;
    getEmployeeById(employeeId).then((res)=>{
      setInfo(res);
    });
    let tempTab = [
      {key: 'basisInfo',tab: '基本信息'},
      {key: 'score', tab: '360评分'},
      {key: 'annex',tab: '附件信息'},
      {key: 'performance',tab: '个人绩效'},
      {key: 'contract',tab: '合同协议'},
      {key: 'attendance',tab: '考勤记录'},
      {key: 'salary', tab: '薪酬福利'},
      {key: 'record',tab: '异动记录'},
      {key: 'internal',tab: '内部奖惩'},
      {key: 'hire',tab: '招聘录用'},
      {key: 'certificate', tab: '证件资质'},
    ];
    let temp = [];
    tempTab.map(item => {
      if(item.key === 'salary'){
        (authorities.indexOf("user:info:salary") > -1) && temp.push({...item});
      }else{
        temp.push({...item})
      }
    });
    setTabList(temp)
  }, []);

  const handleEdit = () => {
    const { employeeId } = props.match.params;
    history.push(`/info/edit/${employeeId}`)
  };

  const handleEmail = () => {
    const { employeeId } = props.match.params;
    history.push(`/recruitment/email/${employeeId}`);
  };

  const handleDelete = () => {
    const { employeeId } = props.match.params;
    deleteEmployeeById(employeeId).then(()=>{
      message.success('删除成功');
      dispatch({
        type: 'infoAndDetails/getEmployeeById',
        payload: employeeId,
      })
    })
  };

  const onTabChange = (tabActiveKey) => {
    setTabActiveKey(tabActiveKey);
  };

  if(!info) return <Result
    status="404"
    title="找不到人员信息"
    subTitle="无此人员或此人员已删除"
    extra={
      <Button type="primary" onClick={() => history.goBack()}>
        返回
      </Button>
    }
  />;

  const action = (
    <RouteContext.Consumer>
      {({  }) => {
        return (
          <Fragment>
            <Button type="primary" onClick={() => history.goBack()}>返回</Button>
            {(info.isHireDone === 0 && info.status === 3) && <Button type="primary" onClick={handleEmail}>发送邮件</Button>}
            {(authorities.indexOf("user:info:edit") > -1) && <Button type="primary" onClick={handleEdit}>修改信息</Button>}
            {
              (authorities.indexOf("emp:operate:delete") > -1 && info.status !== 3) && <Popconfirm title="是否要删除此人？" cancelText='取消' okText='确认' onConfirm={handleDelete}>
                <Button type="primary" >删除</Button>
              </Popconfirm>
            }
          </Fragment>
        )
      }}
    </RouteContext.Consumer>
  );

  const description = (
    <RouteContext.Consumer>
      {({ isMobile }) => (
        <Descriptions className={styles.headerList} size="small" column={isMobile ? 1 : 2}>
          <Descriptions.Item label="性别">{genderList.find(e=>info.gender===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="生日">{info.birthday && moment(info.birthday).format('YYYY-MM-DD')}</Descriptions.Item>
          <Descriptions.Item label="个人电子邮箱">{info.privatemail}</Descriptions.Item>
          <Descriptions.Item label="手机">{info.mobile}</Descriptions.Item>
          <Descriptions.Item label="身份证">{info.idcard}</Descriptions.Item>
          <Descriptions.Item label="参加工作时间">
            {info.beginworkdate && moment(info.beginworkdate).format('YYYY-MM-DD')}
          </Descriptions.Item>
          <Descriptions.Item label="婚姻状况">{maritalList.find(e=>info.marital===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="国籍">{ regionList.find(e=>info.nation===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="户口所在地">{info.regresidence}</Descriptions.Item>
          <Descriptions.Item label="家庭住址">{info.address}</Descriptions.Item>
          <Descriptions.Item label="民族">{nationList.find(e=>info.nationality===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="籍贯">{info.nativeplace}</Descriptions.Item>
          <Descriptions.Item label="政治面貌">{inOrgList.find(e=>info.polity===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="健康状态">{healthsList.find(e=>info.healthstatus===e.value)?.label}</Descriptions.Item>
          <Descriptions.Item label="是否退伍军人">{info.disbandment ? yesOrNoList.find(e=>info.disbandment===e.value)?.label:'否'}</Descriptions.Item>
          <Descriptions.Item label="退伍军人编号">{info.veteranNum}</Descriptions.Item>
        </Descriptions>
      )}
    </RouteContext.Consumer>
  );

  const extra = (
    <div className={styles.moreInfo}>
      {
        info.photoUrl && <div className={styles.photo}>
          <img src={info.photoUrl} alt=""/>
        </div>
      }
    </div>
  );

  return (
    <div className='info-details'>
      {
        (info && info.oid) ? <PageHeaderWrapper
          title={`${info.name}`}
          extra={action}
          className={styles.pageHeader}
          content={description}
          extraContent={extra}
          tabActiveKey={tabActiveKey}
          onTabChange={onTabChange}
          tabList={tabList}
        >
          <div className={styles.main}>
            {tabActiveKey === 'basisInfo' && <BasisInfo info={info} orgLine={orgLine} orgSystem={orgSystem} nativePlace={nativePlace}/>}
            {tabActiveKey === 'score' && <Score oid={props.match.params.employeeId}/>}
            {tabActiveKey === 'annex' && <Annex info={info}/>}
            {tabActiveKey === 'performance' && <Performance code={info.code}/>}
            {tabActiveKey === 'contract' && <Contract oid={props.match.params.employeeId} nativePlace={nativePlace}/>}
            {tabActiveKey === 'attendance' && <Attendance code={info.code}/>}
            {tabActiveKey === 'salary' && <Salary info={info} oid={props.match.params.employeeId} jobLevel={jobLevel}/>}
            {tabActiveKey === 'record' && <Record code={info.code}/>}
            {tabActiveKey === 'internal' && <Internal oid={props.match.params.employeeId}/>}
            {tabActiveKey === 'hire' && <Hire info={info} oid={props.match.params.employeeId}/>}
            {tabActiveKey === 'certificate' && <Certificate oid={props.match.params.employeeId}/>}
          </div>
        </PageHeaderWrapper> : <div className='spin-block'><Spin size="large"/></div>
      }
    </div>
  )
};

export default connect(({ user, infoAndDetails, loading ,infoModel}) => ({
  infoModel,
  currentUser: user.currentUser,
  infoAndDetails,
  loading: loading.effects['infoAndDetails/getEmployeeById'],
}))(Details)
